package com.edu.redis.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @作者 five-five
 * @创建时间 2021/6/15
 */
@RestController
@Api("RedisTestController(Redis测试接口)")
public class RedisTestController {
    @Resource
    RedisTemplate redisTemplate = new RedisTemplate();

    @ApiOperation(value = "测试Redis连接",notes = "测试Redis连接")
    @GetMapping("/test")
    public String testRedis() {
        //设置值到redis中
        redisTemplate.opsForValue().set("name", "lucy");
        //从redis中获取值
        String name = String.valueOf(redisTemplate.opsForValue().get("name"));
        return name;
    }

    @ApiOperation(notes = "测试Redis实现分布式锁",value = "测试Redis实现分布式锁")
    @GetMapping("/testLock")
    public void testLock() {
        //1获取锁，setne
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", "111");
        //2获取锁成功、查询num的值
        if (lock) {
            String value = String.valueOf(redisTemplate.opsForValue().get("num"));
            //2.1判断num为空return
            if (StringUtils.isEmpty(value)) {
                return;
            }
            //2.2有值就转成成int
            int num = Integer.parseInt(value + "");
            //2.3把redis的num加1
            redisTemplate.opsForValue().set("num", ++num);
            //2.4释放锁，del
            redisTemplate.delete("lock");
        } else {
            //3获取锁失败、每隔0.1秒再获取
            try {
                Thread.sleep(100);
                testLock();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}
